<?php
class Merchant_Service_AsnProccess
{
	protected $_order = null;	 
	protected $_orderCode = null;
	protected $_plan = null;
	protected $_procCnt  = null;
	protected $_products = null;
	protected $_customerId = null;
	protected $_customerInfo = null;
	protected $_error;
	protected $_pro;
	
	public function __construct($pro='R'){			
		$this->setCustomer();
		$this->_pro = $pro;
	}
	
	private function setCustomer(){	
		if(!isset($this->_customerId)){
			$customerService = new Merchant_Service_Customer();
			$customerInfo = $customerService->getLoginInfo()->customer;
			$this->_customerId = $customerInfo['customer_id'];
			$this->_customerInfo = $customerInfo;
		}
	
	}
	
	/**
	 * 创建一条新的 ASN 信息
	 * 参数 $productArr: 一维数组,索引为产品id，值为 数量
	 */
	public function create($productArr,$row,$customerId=null,$chkArr=null,$priorityArr=null){
		if($customerId) $this->_customerId = $customerId;
		
		$rowLog =array();
		$rowLog['rl_type'] = 0;			//0:内容修改;1:状态修改
		$rowLog['user_id'] = 0;			//用户新创建时
		$rowLog['customer_id'] = $this->_customerId;
		$rowLog['rl_note'] = '';		//待确定
		$rowLog['rl_add_time'] = date('Y-m-d H:i:s');
		$rowLog['rl_ip'] = Default_Service_Common::getIP();
		
		$Obj = new Merchant_Model_Receiving();
		$Obj->getAdapter()->beginTransaction();
		if ($row['ref_id']!=''&!$this->checkReferenceNo($row['ref_id'])){
			$Obj->getAdapter()->rollBack();
			return array('ask'=>0,'receiving_code'=>'','msg'=>'Reference No. existed');
		}
		try{
			$code = $this->createAsnCode();	// 返回一个新的相应asn code 
			$code && $row['receiving_code'] = $code;
			$rowLog['receiving_code'] = $code;
			$lastInsertId = $Obj->add($row);
			$this->createAsnItem($productArr,$code,$chkArr,$priorityArr);
			$this->createAsnLog($rowLog);	  // 创建日志
			$Obj->getAdapter()->commit();
		}catch (Exception $e) {
			//echo $e->getTraceAsString();
			//echo $e->getMessage();
			$Obj->getAdapter()->rollBack();
			return array('ask'=>0,'receiving_code'=>'','msg'=>'Create asn failed ： '.$e->getMessage());
		}
		$arr =  array('ask'=>'Success','receiving_code'=>$code,'msg'=>'Success');
		return $arr;
	}
	
	public function createAsnItem($productArr,$code,$chkArr=null,$priorityArr=null){
		if(!$productArr || !$code){
			throw new Exception('productId or receiving_code error.');
		}
		$cdate = date('Y-m-d H:i:s');
		$itemIdArr = array();
		$obj = new Merchant_Service_ReceivingItem;
		foreach ($productArr as $key =>$val ){
			$result = $this->checkProductStatus($key);
			if(!isset($result['ask']) || $result['ask']=='0' ){
				throw new Exception($result['productInfo']['product_sku'].' the product status must be activated.');
			}
			if($val<1){
				throw new Exception($result['productInfo']['product_sku']." Quantity can't for empty.");
			}
			$itemArr = array();
			$itemArr['receiving_code'] = $code;
			$itemArr['product_id'] = $key;
			$itemArr['order_qty'] = $val;
			$itemArr['created'] = $cdate;
			if(isset($chkArr[$key])){
				$itemArr['is_qc'] = $chkArr[$key];
			}
			if(isset($priorityArr[$key])){
				$itemArr['ri_sort'] = $priorityArr[$key];
			}
			$obj = new Merchant_Service_ReceivingItem;
			$itemId = $obj->add($itemArr);
		}
	}
	
	/**
	 * 更新指定的 ASN 信息
	 * 参数 $productArr: 一维数组,索引为产品id，值为 数量
	 */
	public function update($productArr,$row,$value,$field,$chkArr=null,$priorityArr=null){
		if(isset($row['ref_id'])){
			unset($row['ref_id']);
		}
		
		$Obj = new Merchant_Model_Receiving();
		$rows_affected = $Obj->update($row,$value,$field);
		$info = $Obj->getByValue($value,$field);
		$Obj->getAdapter()->beginTransaction();
		
		$rowLog =array();
		$rowLog['receiving_code'] = $info['receiving_code'];
		$rowLog['rl_type'] = 0;		//0:内容修改;1:状态修改
		$rowLog['user_id'] = 0;		//用户新创建时
		$rowLog['customer_id'] = $this->_customerId;
		$rowLog['rl_note'] = '';	//待确定
		$rowLog['rl_add_time'] = date('Y-m-d H:i:s');
		$rowLog['rl_ip'] = Default_Service_Common::getIP();				
		try{
			
			$res = Merchant_Service_ReceivingItem::delete($info['receiving_code'],'receiving_code');
			$this->createAsnItem($productArr,$info['receiving_code'],$chkArr,$priorityArr);
			$this->createAsnLog($rowLog);		//	创建日志
			$Obj->getAdapter()->commit();
		}catch (Exception $e) {
			echo $e->getTraceAsString();
			echo $e->getMessage();
			$Obj->getAdapter()->rollBack();
			return array('ask'=>0,'msg'=>'Edit asn failed');
		}
		
		return array('ask'=>'Success','receiving_code'=>$info['receiving_code'],'msg'=>'Success');
	}
	
	/**
	 * 	检查 receiving 表 ref_id 字段值(客户参考号)的唯一性
	 *  $reference_no已存在返回 false;不存在返回 true; 
	 */
	public function checkReferenceNo($reference_no){		
		$row = Merchant_Service_Receiving::getByValue($reference_no,'ref_id');
		if($row){
			return false;
		}else {
			return true;
		}
	}
	
	/**
	 *  检查产品状态是否激活
	 *  激活返回 true，其他返回产品详细array()
	 */
	
	public function checkProductStatus($productId,$customerId = null){
		if(!$customerId){
			$customerId = $this->_customerId;
		}
		$productObj = Merchant_Service_Product::getInstance();
		$productInfo = $productObj->getProductInfo($productId,$customerId);
		if(isset($productInfo['product_status'])&& $productInfo['product_status']==1){
			return array('ask'=>1,'productInfo'=>$productInfo);
		}
        return array('ask'=>0,'productInfo'=>$productInfo);
		
	}

	
	/**
	 * 	针对指定用户，生成一个新的相应 code  独立事务
	 */
	public function createCode(){
		$lastCode = $ASNNo = $tmp = '';	
		$Obj = new Merchant_Model_Receiving();	
		$ObjReceiving = new Merchant_Service_Receiving();
		$Obj->getAdapter()->beginTransaction();		 
		//发货
		$order_type = $this->_pro=="R"?1:4;
		$lastCode = $ObjReceiving->getCurdateLastCode($this->_customerId,$order_type);
		$Obj->getAdapter()->commit();
		
		$ASNNo = $this->_pro.$this->_customerId.date('ymd');

		if($lastCode){
			$tmp= (int) substr($lastCode,-3,3);				
			$tmp= str_pad(($tmp+1),3,'0',STR_PAD_LEFT);
		}else{
			$tmp ='001';
		}
		$ASNNo .= $tmp;		
		return $ASNNo;
	}
	
	/**
	 * 	针对指定用户，生成一个新的相应 AsnCode 无事务
	 */
	public function createAsnCode(){
		$lastCode = $ASNNo = $tmp = '';	
		$Obj = new Merchant_Model_Receiving();	
		$ObjReceiving = new Merchant_Service_Receiving();
		$order_type = $this->_pro=="R"?1:4;
		$lastCode = $ObjReceiving->getCurdateLastCode($this->_customerId,$order_type);
		
		$ASNNo = $this->_pro.$this->_customerId.date('ymd');

		if($lastCode){
			$tmp= (int) substr($lastCode,-3,3);				
			$tmp= str_pad(($tmp+1),3,'0',STR_PAD_LEFT);
		}else{
			$tmp ='001';
		}
		$ASNNo .= $tmp;
		return $ASNNo;
	}
	
	/**
	 * 	创建日志
	 */
	public function createAsnLog($row){
		
		$res = Merchant_Service_ReceivingLog::add($row);		
	}
	 
	 /*
	 *验证
	 */
	 
	/**
	 * 根据ASN订单号，获取ASN信息
	 */
	public function getAsnInfo($receiving_code,$customerId){
		
		$obj = new Merchant_Service_Receiving();
		$Itemobj = new Merchant_Service_ReceivingItem();
		$productModel = new Merchant_Model_Product();
		$putawayModel = new Merchant_Model_Putaway();
		
		$rcRow=$obj->getByValue($receiving_code,'receiving_code');
		if(!$rcRow) return;
		//if($rcRow['customer_id']!=$customerId) return;
		$ItemRows=$Itemobj->getAllByValue($receiving_code,'receiving_code');
		$status=$rcRow['status']; //ASN状态
		$AsnDetail=array();
        if(!$ItemRows) return;
		foreach($ItemRows as $key => $val){
			$productRow=$productModel->getProduct($val['product_id'],$rcRow['customer_id']);
            $putaway_quantity=0;
            /*$condition=array(
				'receiving_code'=>$val['receiving_code'],
				'product_id'=>$val['product_id'],
				'warehouse_id'=>$rcRow['warehouse_id'],
				'putaway_status'=>1,//已完成
			);
			$putawayRows=$putawayModel->getByCondition($condition,'*');
			if(!empty($putawayRows)){
				foreach($putawayRows as $k => $v){
					$putaway_quantity+=$v['putaway_quantity'];
				}
			}
            */
            $putaway_quantity=$val['putaway_qty'];
//             if($putaway_quantity>0){
//             	$status=3;
//             }
			//判断有没哟收货人
			$val['modified_by']&&$rowUser = Merchant_Service_User::getByUserId($val['modified_by']);
			$AsnDetail[]=array(
				'sku'=>$productRow['product_sku'],
				'quantity'=>$putaway_quantity,//已完成上架数量
				'weight'=>$val["status"]!=3?0:$val['weight'],
				'isQC'=>$val['is_qc'],
				'priorityLevel'=>$val['ri_sort'],
				'receiveUser'=>!empty($rowUser)?$rowUser['name']:"",//收货人 2012年6月15日
				'receiveTime'=>$val['receivetime'],//收货日期 2012年6月15日
				'receiveRemark'=>$val['remark'],//收货差异备注 2012年6月15日
			);

			
		}
		
		$AsnData=array(
			'AsnCode'=>$rcRow['receiving_code'],
			'AsnCreateTime'=>$rcRow['created'],
			'AsnLastUpdate'=>$rcRow['modified'],
			'AsnStatu'=>$status,			
			'AsnDetail'=>$AsnDetail,
			'ASNspecial'=>$rcRow['order_type']==4?"Y":"N",//是否特采 2012年6月15日
		);
        
        //Qc Info Below:
		$qcoRes = Merchant_Service_QualityControlOrder::getByQcoRefCode($receiving_code);
        $QcDetail=array();
		if(!empty($qcoRes)){
			$pocModel = Merchant_Model_ProductOptionChoose::getInstance();
			foreach($qcoRes as $key=>$val){
				//Qc Item Row
				$qciRow = Merchant_Service_QualityControlItem::getByQcoCode($val['qco_code']);
				$productRow = $productModel->getProduct($qciRow['product_id'],$val['customer_id']);
				//Qc Result Res
				$qcrRes = Merchant_Service_QualityControlResult::getQciIdAll($qciRow['qci_id']);
				$QcInfo=array();
				if(!empty($qcrRes)){
					foreach($qcrRes as $k=>$v){
						$poValue='';
						//Pov Row
						$povRow = Merchant_Service_ProductOptionValue::getByPovId($v['pov_id']);
						//Poc Row
						if(!empty($povRow)){
							$poValue = $povRow['po_value'];
							$pocRow = $pocModel->getByPocid($povRow['poc_id']);
						}

						$QcInfo[] = array(
							'optionName'=>isset($pocRow['poc_value_cn'])?$pocRow['poc_value_cn']:'',
							'optionValue'=>$poValue,
							'optionProblemQuantity'=>$v['qcr_quantity_problem'],
							'optionNote'=>$v['qcr_description'],
							'createTime'=>$v['qcr_create_time'],
						);
					}
				}
				
				$userRow = Merchant_Service_User::getByUserId($qciRow['user_id']);
				$QcDetail[]=array(
                    'QCCode'=>$val['qco_code'],
					'qcTime'=>$qciRow['qci_last_update'],//质检时间	2012年6月15日	 			
					'operator'=>$userRow['name'],
					'statu'=>$val['qco_status'],
					'sku'=>$productRow['product_sku'],
					'quantity'=>$val['qco_real_quantity'],//实收数量
					'problemQuantity'=>$val['qco_quantity_problem'],
					'putawayQuantity'=>$qciRow['qci_putaway_qty'],
                    'QCNote'=>$val['qco_note'],
                    'lastUpdate'=>$qciRow['qci_last_update'],
					'info'=>$QcInfo,
				);
			}
		}
		$AsnData['QCDetail'] = $QcDetail;
		return $AsnData;
	}
	
	
	/**
	 * 删除asn产品
	 */
	public function deleteAsnProduct($receiving_code,$skus,$customerId){
	
		$obj = new Merchant_Service_Receiving();
		$modelReceiving = new Merchant_Model_Receiving();
		$Itemobj = new Merchant_Service_ReceivingItem();
		$productModel = new Merchant_Model_Product();
		$putawayModel = new Merchant_Model_Putaway();
		$modelReceiving->getAdapter()->beginTransaction();
		
		try{	
			
			if(empty($receiving_code)||empty($skus)||empty($customerId)){
				throw new Exception( "request data error!!");
			}		
			$rcRow=$obj->getByValue($receiving_code,'receiving_code');
			if(!$rcRow) {
				throw new Exception( "AsnCode:$receiving_code can not be found");
			}
			if($rcRow['customer_id']!=$customerId) {
				throw new Exception( "AsnCode:$receiving_code can not be found.");
			}
			$status=$rcRow['status']; //ASN状态
			
			
			if(!in_array($status, array(0,1))){	//delete和awaiting状态可删除asn产品	
					
				throw new Exception("permission deny,AsnCode:$receiving_code statu is not allow.");
			}
			$ItemRows=$Itemobj->getAllByValue($receiving_code,'receiving_code');
			$productIds = array();
			foreach($ItemRows as $key => $val){
				$productIds[] = $val['product_id'];
					
			}
			$productObj = new Merchant_Service_Product();
			$delCount = 0;
			$msg = "接口删除asn订单行:asnCode:".$receiving_code."\n";
			foreach($skus as $sku){
						
				$product = Merchant_Model_Product::getInstance()->getProductBySku($sku,$customerId);
				if($product instanceof Zend_Db_Table_Row){
					$product = $product->toArray();					
				}else{
					throw new Exception( "AsnCode:$receiving_code ,sku: $sku is not exists");
				}
				
				
				if(in_array($product['product_id'],$productIds)){
					$con = array("product_id"=>$product['product_id'],"receiving_code"=>$receiving_code);
					$list = $Itemobj->getByCond($con, "*", "", 0, 0);
					if(empty($list)){
						throw new Exception( "AsnCode:$receiving_code ,sku: $sku is not exists");
					}
					$msg.="delete ri_id={$list[0]['ri_id']} sku={$sku} product_id={$list[0]['product_id']}\n";
					$Itemobj->delete($list[0]['ri_id'], "ri_id");//删除item
					$delCount++;				
					
				}else{
					throw new Exception( "AsnCode:$receiving_code ,sku: $sku is not belong this AsnCode");
					
				}
			}
			if($delCount==count($productIds)){//删除的sku数量与$receiving_code的sku数量 一致 ，删除该receive_code
				$msg.="all receive_item deleted,delete asn $receiving_code";
				$obj->delete($receiving_code,'receiving_code');//删除asn
			}
		
			
			$rowLog =array();
			$rowLog['receiving_code'] = $receiving_code;
			$rowLog['rl_type'] = 0;			//0:内容修改;1:状态修改
			$rowLog['user_id'] = 0;			//系统
			$rowLog['customer_id'] = $customerId;
			$rowLog['rl_note'] = $msg;		//日志内容
			$rowLog['rl_add_time'] = date('Y-m-d H:i:s');
			$rowLog['rl_ip'] = Default_Service_Common::getIP();
				
			$this->createAsnLog($rowLog);	  // 创建日志
			
			$modelReceiving->getAdapter()->commit();
		
		}catch (Exception $e){			
			return $e->getMessage();
		}
		return true;
	}
	
	public function updateReceive($receivingCode,$receivingArr,$receiveItem,$customerId){//接口方法，更新asn和订单行
		$obj = new Merchant_Service_Receiving();
		$modelReceiving = new Merchant_Model_Receiving();
				
		$modelReceiving->getAdapter()->beginTransaction();		
		try{
				
			if(empty($receivingCode)||empty($customerId)){
				throw new Exception( "request data error!!");
			}
			$rcRow=$obj->getByValue($receivingCode,'receiving_code');
			if(!$rcRow) {
				throw new Exception( "AsnCode:$receivingCode can not be found");
			}
			if($rcRow['customer_id']!=$customerId) {
				throw new Exception( "AsnCode:$receivingCode can not be found.");
			}
			$status=$rcRow['status']; //ASN状态				
				
			if(!in_array($status, array(0,1))){	//delete和awaiting状态可删除asn产品
					
				throw new Exception("permission deny,AsnCode:$receivingCode statu is not allow.");
			}
// 			print_r($receivingArr);exit;
			$msg .= "接口数据更新：receiving_code : ".$receivingCode." data changed :";
			foreach($receivingArr as $column=>$v){
				$msg.=$column." from ".$rcRow[$column]." to ".$v.";";
			}
			$msg.="\n";
			
			if(!empty($receivingArr)&&!$obj->update($receivingArr, $receivingCode, "receiving_code")){//需要更新且更新失败 报异常
				throw new Exception("AsnCode:$receivingCode update fail");
			}

			$returnMsg = $this->updateReceiveItem($receivingCode,$receiveItem,$customerId);//更新订单行
			
			$msg.=$returnMsg;
			
			$rowLog =array();
			$rowLog['receiving_code'] = $receivingCode;
			$rowLog['rl_type'] = 0;			//0:内容修改;1:状态修改
			$rowLog['user_id'] = 0;			//系统
			$rowLog['customer_id'] = $customerId;
			$rowLog['rl_note'] = $msg;		//日志内容
			$rowLog['rl_add_time'] = date('Y-m-d H:i:s');
			$rowLog['rl_ip'] = Default_Service_Common::getIP();
			
			$this->createAsnLog($rowLog);	  // 创建日志
			
			$modelReceiving->getAdapter()->commit();
		
		}catch (Exception $e){
			return $e->getMessage();
		}
		return true;
	}
	
	
	private function updateReceiveItem($receivingCode,$receiveItems,$customerId){//更新订单行,禁止外部单独调用
		$Itemobj = new Merchant_Service_ReceivingItem();
        $obj = new Merchant_Service_Receiving();
        $rcRow=$obj->getByValue($receivingCode,'receiving_code');
		$ItemRows=$Itemobj->getAllByValue($receivingCode,'receiving_code');
		$productIds = array();
		foreach($ItemRows as $key => $val){
			$productIds[] = $val['product_id'];
				
		}
		$productObj = new Merchant_Service_Product();

		$msg = "";//日志内容
		foreach($receiveItems as $item){
			$sku = $item['product_sku'];
			unset($item['product_sku']);
			
			$product = Merchant_Model_Product::getInstance()->getProductBySku($sku,$customerId);
			if($product instanceof Zend_Db_Table_Row){
				$product = $product->toArray();
			}else{
				throw new Exception( "AsnCode:$receivingCode , sku: $sku can not be found.");
			}		
		
			if(in_array($product['product_id'],$productIds)){
				$con = array("product_id"=>$product['product_id'],"receiving_code"=>$receivingCode);
				$list = $Itemobj->getByCond($con, "*", "", 0, 0);
				if(empty($list)){
					throw new Exception( "AsnCode:$receivingCode ,sku: $sku is not exists");
				}
                //修改特采类型，应判断数量
				if($rcRow['order_type']==4){
                    $productStocketRow = Merchant_Service_ProductStocket::getByProductId($product['product_id'],1);
                    if(empty($productStocketRow) || $productStocketRow['ps_quantity_problem'] < $item['order_qty'] ){
                        throw new Exception( "SKU:".$sku." problem quantity is ".(isset($productStocketRow['ps_quantity_problem'])?$productStocketRow['ps_quantity_problem']:0).", less than ".$item['order_qty'].'.');
                    }
                }
				$msg .= "ri_id : ".$list[0]['ri_id']." data changed :";
				foreach($item as $column=>$v){
					$msg.=$column." from ".$list[0][$column]." to ".$v.";";
				}
				$msg.="\n";
				
				if(!$Itemobj->update($item,$list[0]['ri_id'], "ri_id")){//更新item
					throw new Exception( "AsnCode:$receivingCode ,sku: $sku  update AsnItem fail");
				}					
		
			}else{
				throw new Exception( "AsnCode:$receivingCode ,sku: $sku is not belong this AsnCode");
		
			}
		}
		
		return $msg;
			
	}
}
?>